package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    //1.第一步，先创建一个socket对象
    private DatagramSocket socket=null;
    private String serverIp;
    private int serverPort;
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        socket=new DatagramSocket();
        this.serverIp=serverIp;
        this.serverPort=serverPort;
    }
    public void start() throws IOException {
        System.out.println("client start!");
        Scanner scanner=new Scanner(System.in);
        while (true){
            //2.用户在控制台上进行输入
            System.out.println("->");
            String request=scanner.next();
            if(request.equals("exit")){
                break;
            }
            //3.把用户输入的字符串构造成 UDP 数据报, 进行发送.
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(this.serverIp)
            ,this.serverPort);
            socket.send(requestPacket);
            //4.读取服务器的响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            //将二进制文件转化为字符串类型
           String response=new String(responsePacket.getData(),0, responsePacket.getLength());
           //5.显示（打印）响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient=new UdpEchoClient(" ",);
        udpEchoClient.start();
    }
}